# -*- coding: utf-8 -*-
__author__ = 'Paul'
from plone.memoize.instance import memoize
from plone.memoize import ram
from plone.memoize.compress import xhtml_compress
from plone.portlets.interfaces import IPortletDataProvider
from plone.app.layout.navigation.root import getNavigationRootObject
from zope.component import getMultiAdapter
from zope.formlib import form
from zope.interface import implements
from zope import schema

from Acquisition import aq_inner
from DateTime.DateTime import DateTime
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from plone.app.portlets import PloneMessageFactory as _
from plone.app.portlets.cache import render_cachekey
from plone.app.portlets.portlets import base


class IBpEventoPortlet(IPortletDataProvider):
    count = schema.Int(title=_(u'Number of items to display'),
        description=_(u'How many items to list.'),
        required=True,
        default=5)

    state = schema.Tuple(title=_(u"Workflow state"),
        description=_(u"Items in which workflow state to show."),
        default=('published', ),
        required=True,
        value_type=schema.Choice(
            vocabulary="plone.app.vocabularies.WorkflowStates")
    )


class Assignment(base.Assignment):
    implements(IBpEventoPortlet)

    def __init__(self, count=5, state=('published', )):
        self.count = count
        self.state = state

    @property
    def title(self):
        return _(u"Eventos de la BP")


class Renderer(base.Renderer):

    _template = ViewPageTemplateFile('bpEventos_portlet.pt')
    nomMeses=("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)

        portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state')
        self.navigation_root_url = portal_state.navigation_root_url()
        self.portal = portal_state.portal()
        self.navigation_root_path = portal_state.navigation_root_path()
        self.navigation_root_object = getNavigationRootObject(self.context, self.portal)

    @ram.cache(render_cachekey)
    def render(self):
        return xhtml_compress(self._template())

    @property
    def available(self):
        return  True
        #return self.data.count > 0 and len(self._data())

    def published_events(self):
        return self._data()


    def dameWeekDay(self,DateTimeObj):
        from datetime import date
        import datetime

        nuevoF=date(DateTimeObj.year(),DateTimeObj.month(),DateTimeObj.day())
        return nuevoF.strftime("%A")

    @memoize
    def have_events_folder(self):
        return 'events' in self.navigation_root_object.objectIds()

    def all_events_link(self):
        evFolder = self.navigation_root_object['intereses']['recreacion']['eventos']
        return evFolder.absolute_url()

        navigation_root_url = self.navigation_root_url
        if self.have_events_folder():
            return '%s/events' % navigation_root_url
        else:
            return '%s/events_listing' % navigation_root_url

    def prev_events_link(self):
        # take care dont use self.portal here since support
        # of INavigationRoot features likely will breake #9246 #9668
        if (self.have_events_folder() and
            'aggregator' in self.navigation_root_object['events'].objectIds() and
            'previous' in self.navigation_root_object['events']['aggregator'].objectIds()):
            return '%s/events/aggregator/previous' % self.navigation_root_url
        elif (self.have_events_folder() and
              'previous' in self.navigation_root_object['events'].objectIds()):
            return '%s/events/previous' % self.navigation_root_url
        return None

    def getNextEvts(self):
        acM=DateTime().month()
        listEvts=[]
        puntero=0
        mesFlag=0

        for evento in self._data():
            objetoMes=self.context.unrestrictedTraverse(evento.getPath())
            if len(listEvts)==0:
                listEvts.append(self.creaObjectoEvento("En este mes"))

            if acM!=evento.start.month():
                if mesFlag>0:
                    break;
                listEvts.append(self.creaObjectoEvento(self.nomMeses[evento.start.month()-1]))
                acM=evento.start.month()
                puntero=0
                mesFlag=mesFlag+1

            nuevoMes=listEvts[mesFlag]
            if len(evento.Description)>200:
                descr=evento.Description[:evento.Description[:200].rindex(" ")]
            else:
                descr=evento.Description

            objMes=dict()
            objMes["titulo"]=evento.Title
            objMes["descri"]= descr
            objMes["url"]   = evento.getURL()
            objMes["fecha"] = self.getCopeteFecha(objetoMes)
            nuevoMes["cantEventos"]=puntero+1
            nuevoMes["eventos"].append(objMes)





        return listEvts


    @memoize
    def _data(self):
        import calendar

        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        limit = self.data.count
        state = self.data.state
        path = self.navigation_root_path

        start =  (DateTime() - (DateTime().day()))
        end = DateTime(DateTime().year(),12,30)


        date_range_query = {'query': (start, end), 'range': 'min:max'}

        result=catalog(portal_type='Products.bpContents.evento',start=date_range_query,sort_on='start',sort_limit=limit)[:limit]


        return result

    def creaObjectoEvento(self,mesName):
        """devuelve un dicionary con el mes vacio"""
        objetoMes=dict()
        objetoMes["titulo"]=mesName
        objetoMes["url"]=""
        objetoMes["eventos"]=[]
        objetoMes["cantEventos"]=0
        return objetoMes

    def getCopeteFecha(self,objEvt):
        """devuelve string para poner de copete"""

        strA="Del 1 al 5 de Marzo, 18hs"
        inicio=objEvt.start
        fin=objEvt.end
        diaA=DateTime(inicio).day()
        diaB=DateTime(fin).day()
        mesaA=self.nomMeses[int(DateTime(inicio).month())-1]
        mesB=self.nomMeses[int(DateTime(fin).month())-1]

        if(DateTime(inicio).minute()!=0):
            horaIni="%s:%s" %(DateTime(inicio).hour(),DateTime(inicio).minute())
        else:
            horaIni=DateTime(inicio).hour()

        if(DateTime(fin).minute()!=0):
            horaFin="%s:%s" %(DateTime(fin).hour(),DateTime(fin).minute())
        else:
            horaFin=DateTime(fin).hour()


        if mesaA==mesB:
            if diaA==diaB:
                strA="%s de %s a las %s" %(diaA,mesaA,horaIni)
            else:
                if objEvt.esRango:
                    strA="Del %s al %s de %s, %shs." %(diaA,diaB, mesaA,horaIni)
                else:
                    strA="%s y %s de %s a las %shs" %(diaA,diaB, mesaA,horaIni)
        else:
            if objEvt.esRango:
                strA="Del %s del %s al %s de %s, a las %shs." %(diaA,mesaA,diaB,mesB,horaIni)
            else:
                strA="%s de %s al %s de %s, a las %shs." %(diaA,mesaA,diaB,mesB,horaIni)

        return strA


    def traducimeDia(self,dia):
        listado=('LUNES','MONDAY','MARTES','TUESDAY','MIÉRCOLES','WEDNESDAY','JUEVES','THURSDAY','VIERNES','FRIDAY','SÁBADO','SATURDAY','DOMINGO','SUNDAY')
        dia = listado[listado.index(dia.upper())-1]
        return dia

class AddForm(base.AddForm):
    form_fields = form.Fields(IBpEventoPortlet)
    label = _(u"Add Events Portlet")
    description = _(u"This portlet lists upcoming Events.")

    def create(self, data):
        return Assignment(count=data.get('count', 5), state=data.get('state', ('published', )))


class EditForm(base.EditForm):
    form_fields = form.Fields(IBpEventoPortlet)
    label = _(u"Edit Events Portlet")
    description = _(u"This portlet lists upcoming Events.")

